package com.knowledge.share.service.websocket;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.knowledge.share.pojo.WsClientInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@CrossOrigin("*")
@ServerEndpoint("/chat/{user}")
public class ChatServer {

    //在线人数
    private static int onlineNum=0;

    //线程安全用来存储在线的用户信息
    ConcurrentHashMap<String,WsClientInfo> chatInfo =new ConcurrentHashMap<String, WsClientInfo>();

    private Session session;
    //链接客户端的id信息
    private String user="";

    @OnOpen
    public void onOpen(Session session, @PathParam("user") String user) throws JsonProcessingException {
        this.session = session;
        this.user = user;

        if(chatInfo.containsKey(user)){
            log.info("用户{}已经链接websocket了",user);
            throw new RuntimeException("已经链接过了");
        }

        //客户端信息实例化对象
        WsClientInfo wsClientInfo = new WsClientInfo();
        wsClientInfo.setToken(user);
        wsClientInfo.setSession(session);
        //添加到安全线程的对象中去
        chatInfo.put(user,wsClientInfo);
        addOnlineNum();//增加一次在线人数的总人数信息

        log.info("用户{}上线，在线人数:{}",user,getOnlineNum());
        sendMessage("请求链接成功");
    }


    /**
     * @desc 发送消息的提示信息
     * @param message
     */
    public void sendMessage(String message) throws JsonProcessingException {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("msg",message);
        hashMap.put("onlineNum",message);
        ObjectMapper mapper = new ObjectMapper();
        String data = mapper.writeValueAsString(hashMap);
        try{
            //发送消息给当前连接的用户信息
            this.session.getAsyncRemote().sendText(data);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //在线人数的相关方法
    public static synchronized int getOnlineNum(){
        return onlineNum;
    }
    public static synchronized void addOnlineNum(){
        ChatServer.onlineNum++;
    }
    public static synchronized void subOnlineNum(){
        ChatServer.onlineNum--;
    }
}
